package com.linghang.controller;

import com.google.gson.Gson;
import com.linghang.dao.ProductDao;
import com.linghang.mybatis.MybatisUtil;
import com.linghang.response.R;
import org.apache.ibatis.session.SqlSession;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author qyyzxty@icloud.com
 * @data 2021/4/29
 **/
public class ProductController extends HttpServlet {

    //获取SqlSession对象
    public static SqlSession sqlSession = MybatisUtil.getSqlSession();

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 解决post请求中文乱码问题
        // 一定要在获取请求参数之前调用才有效
        req.setCharacterEncoding("UTF-8");
        // 解决响应中文乱码
        resp.setContentType("text/html; charset=UTF-8");
        ProductDao productDao = sqlSession.getMapper(ProductDao.class);
        try {
            R result = new R(0, "success", productDao.getAllProducts(null));
            String s =  new Gson().toJson(result);
            resp.getWriter().write(s);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {

    }
}
